import { defineStore } from 'pinia'
import * as api from '../services/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: {
      id: localStorage.getItem('userId') ? parseInt(localStorage.getItem('userId')) : null,
      username: localStorage.getItem('username') || null
    }
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.user.id
  },
  
  actions: {
    async login(username, pwd) {
      try {
        const response = await api.login(username, pwd)
        
        // 根据后端实际响应格式处理数据
        // 后端成功返回: { errno: 0, data: { id, username } }
        // 后端失败返回: { errno: 1, message: "not such user!!" }
        
        if (response && response.errno === 0 && response.data) {
          const userData = response.data
          
          this.user = {
            id: userData.id,
            username: userData.username
          }
          
          // 存储到localStorage
          localStorage.setItem('userId', userData.id.toString())
          localStorage.setItem('username', userData.username)
          
          return { success: true, data: userData }
        } else {
          const errorMsg = response?.message || '登录失败'
          return { success: false, message: errorMsg }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: '登录失败：' + (error.message || '网络错误') }
      }
    },
    
    async register(userData) {
      try {
        const response = await api.register(userData)
        
        // 根据后端实际响应格式处理数据
        // 后端成功返回: { insertId: 新用户ID }
        // 后端失败返回: { errno: 10001, message: '用户名已存在' }
        
        if (response && response.insertId) {
          return { success: true, data: response }
        } else if (response && response.errno) {
          // 处理业务错误（如用户名已存在）
          return { success: false, message: response.message || '注册失败' }
        } else {
          return { success: false, message: '注册失败：未知错误' }
        }
      } catch (error) {
        console.error('注册失败:', error)
        return { success: false, message: '注册失败：' + (error.message || '网络错误') }
      }
    },
    
    logout() {
      this.user = {
        id: null,
        username: null
      }
      
      // 清空localStorage
      localStorage.removeItem('userId')
      localStorage.removeItem('username')
    }
  }
})